package org.example.config;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;

import java.util.*;

public class ExcelConfig
{
    public enum ReadMode {
        BY_HEADER//标题读取
        , BY_INDEX//列读取
    }
    public static class ReadConfig
    {
        private ReadMode mode;
        private String headerName;  // 用于BY_HEADER模式
        private int columnIndex;    // 用于BY_INDEX模式
        private int headerRow = 0;  // 标题行索引（0-based）
        private int dataStartRow = 1; // 数据起始行（0-based）

        // 按标题读取的配置
        public static ReadConfig byHeader(String headerName, int headerRow) {
            ReadConfig config = new ReadConfig();
            config.mode = ReadMode.BY_HEADER;
            config.headerName = headerName;
            config.headerRow = headerRow;
            config.dataStartRow = headerRow + 1;
            return config;
        }

        // 按列索引读取的配置
        public static ReadConfig byIndex(int columnIndex, int dataStartRow) {
            ReadConfig config = new ReadConfig();
            config.mode = ReadMode.BY_INDEX;
            config.columnIndex = columnIndex;
            config.dataStartRow = dataStartRow;
            return config;
        }
    }
    /**
     * 读取Excel中的学生姓名
     * @param filePath Excel文件路径
     * @param config 读取配置
     * @return 学生姓名列表
     */
    public List<String> readStudentNames(String filePath, ReadConfig config) {
        switch (config.mode) {
            case BY_INDEX:
                return readByIndex(filePath, config);
            default:
                throw new IllegalArgumentException("不支持的读取模式");
        }
    }
    /**
     * 按列索引读取模式
     */
    private List<String> readByIndex(String filePath, ReadConfig config) {
        List<String> names = new ArrayList<>();
        EasyExcel.read(filePath, new ReadListener<Map<Integer, String>>() {
            @Override
            public void invoke(Map<Integer, String> data, AnalysisContext context) {
                // 跳过数据起始行之前的数据
                if (context.readRowHolder().getRowIndex() < config.dataStartRow) {
                    return;
                }

                String name = data.get(config.columnIndex);
                if (name != null && !name.trim().isEmpty()) {
                    names.add(name.trim());
                }
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {

            }
        }).sheet().headRowNumber(0).doRead();

        return names;
    }
}
